/*
 * @Author: fengYM feng25321@163.com
 * @Date: 2023-09-25 10:34:21
 * @LastEditors: fengYM feng25321@163.com
 * @LastEditTime: 2023-10-12 16:57:57
 * @Description:api.ts
 */
// export const BASE_URL = "http://192.168.3.82:8080/fyapp"; // 开发
export const BASE_URL = "http://47.121.212.148/fyapp"; // 线上
export const BASE_UPLOADURL = BASE_URL + "/uploadHeadImg.do";
import params from "./publicParams";
// 统一的异常处理函数
function handleRequestError(error: any) {
  uni.showToast({
    title: error || "网络请求失败",
    icon: "none",
    duration: 2000,
  });
  console.error("请求失败：", error);
}
// 发送请求的封装
export function apiRequest(config: any): any {
  config.url = `${BASE_URL}${config.url}`;
  config.data = {
    ...params,
    ...config.data,
  };
  config.header = { "Content-Type": "application/x-www-form-urlencoded" };

  let thePages: any = getCurrentPages();
  const pageName = thePages[thePages.length - 1].route;
  if (pageName !== "pages/shop/shop" && pageName !== "pages/zcsj/zcsj") {
    uni.showLoading({
      title: "加载中",
    });
  }
  return new Promise((resolve, reject) => {
    uni.request({
      ...config,
      success(response: { data: any }) {
        uni.hideLoading();
        const data = response.data;
        if (data.bizSucc) {
          resolve(data);
        } else {
          handleRequestError(data.errMsg);
          reject(new Error(data.errMsg || "请求失败"));
        }
      },
      fail(error: any) {
        uni.hideLoading();
        // 统一异常处理
        handleRequestError(error);
        reject(error);
      },
      complete() {
        //隐藏loading
      },
    });
  });
}
